<?php

namespace app\controller;

use app\BaseController;
use app\model\SysMenu;
use app\model\User as UserModel;
use mikkle\tp_auth\WlAuthAction;
use mikkle\tp_wechat\WechatApi;
use think\Exception;
use think\facade\Cache;
use think\facade\Config;
use think\facade\Db;
use think\facade\Request;
use think\facade\Route;
use think\facade\Session;
use think\helper\Str;
use think\captcha\facade\Captcha;
use app\controller\CommonPayController;
use mikkle\tp_auth\AuthWeb;
use think\response\Redirect;
use think\facade\Log;

class ShopController extends BaseController
{

    protected static $url = 'kouzhao.wanglanglang.com';

    protected static $sellNum = 20;

    public function getShopList(Request $request)
    {
        $userName = $request::param('username');

        $list = Db::name('shop_info')->where('is_open', '=', 1)->order('category')->select();
        $time = time();
        $date = toDate($time, 'Y-m-d');
        $time12 = strtotime($date . ' 12:00:00');
        $time1230 = strtotime($date . ' 12:30:00');
        $time13 = strtotime($date . ' 13:00:00');
        $time1330 = strtotime($date . ' 13:30:00');
        $time14 = strtotime($date . ' 14:00:00');

        $time24 = strtotime($date . ' 23:59:00');

        $retList = [];
        foreach ($list as $key => $value) {
            switch ($value['category']) {
                case 1:
                    $title = '12:00后开始预约';
                    if ($time > $time12) {
                        $value['isSub'] = 1;
                        $value['subTitle'] = $value['num'] == 0 ? '预约售罄' : '可以预约';
                    } else {
                        $value['isSub'] = 2;
                        $value['subTitle'] = $title;
                    }
                    break;
                case 2:
                    $title = '12:30后开始预约';
                    if ($time > $time1230) {
                        $value['isSub'] = 1;
                        $value['subTitle'] = $value['num'] == 0 ? '预约售罄' : '可以预约';
                    } else {
                        $value['isSub'] = 2;
                        $value['subTitle'] = $title;
                    }
                    break;
                case 3:
                    $title = '13:00后开始预约';
                    if ($time > $time13) {
                        $value['isSub'] = 1;
                        $value['subTitle'] = $value['num'] == 0 ? '预约售罄' : '可以预约';
                    } else {
                        $value['isSub'] = 2;
                        $value['subTitle'] = $title;
                    }
                    break;
                case 4:
                    $title = '13:30后开始预约';
                    if ($time > $time1330) {
                        $value['isSub'] = 1;
                        $value['subTitle'] = $value['num'] == 0 ? '预约售罄' : '可以预约';
                    } else {
                        $value['isSub'] = 2;
                        $value['subTitle'] = $title;
                    }
                    break;
                case 5:
                    $title = '14:00后开始预约';
                    if ($time > $time14) {
                        $value['isSub'] = 1;
                        $value['subTitle'] = $value['num'] == 0 ? '预约售罄' : '可以预约';
                    } else {
                        $value['isSub'] = 2;
                        $value['subTitle'] = $title;
                    }
                    break;
            }
            $retList[] = $value;
        }
        if ($list !== false) {
            return $this->returnJson(1001, '获取数据成功', $retList);
        } else {
            return $this->returnJson(1002, '可以注册');
        }
    }

    public function createOrder(Request $request)
    {

        $cat_id = $request::post('catId');

        $time = time();
        $date = toDate($time, 'Y-m-d');
        $time12 = strtotime($date . ' 12:00:00');
        $time1230 = strtotime($date . ' 12:30:00');
        $time13 = strtotime($date . ' 13:00:00');
        $time1330 = strtotime($date . ' 13:30:00');
        $time14 = strtotime($date . ' 14:00:00');

        $time24 = strtotime($date . ' 23:59:00');


        $shopSellNum = Cache::get('shopSellTotalNum');

        $sellGoodsNum = self::$sellNum;

        //马坡-牛山
        if ($cat_id == 1) {
            if (!($time > $time12 && $time < $time24)) {
                return $this->returnJson(1002, '还没到开始时间');
            } else {
                $cacheOrder = Cache::get('create_user_order_info' . $cat_id);
                if ($cacheOrder * $sellGoodsNum >= $shopSellNum[1]) {
                    return $this->returnJson(1002, '已经被抢购完毕！');
                } else {
                    Cache::inc('create_user_order_info' . $cat_id);
                }
            }
        }
        //河东镇
        if ($cat_id == 2) {
            if (!($time > $time1230 && $time < $time24)) {
                return $this->returnJson(1002, '还没到开始时间');
            } else {
                $cacheOrder = Cache::get('create_user_order_info' . $cat_id);
                if ($cacheOrder * $sellGoodsNum >= $shopSellNum[2]) {
                    return $this->returnJson(1002, '已经被抢购完毕！');
                } else {
                    Cache::inc('create_user_order_info' . $cat_id);
                }
            }
        }
        if ($cat_id == 3) {
            //城区府前街以南（含鑫海韵通百货）
            if (!($time > $time13 && $time < $time24)) {
                return $this->returnJson(1002, '还没到开始时间');
            } else {
                $cacheOrder = Cache::get('create_user_order_info' . $cat_id);
                if ($cacheOrder * $sellGoodsNum >= $shopSellNum[3]) {
                    return $this->returnJson(1002, '已经被抢购完毕！');
                } else {
                    Cache::inc('create_user_order_info' . $cat_id);
                }
            }
        }
        if ($cat_id == 4) {
            //河西镇街（除以上地区）
            if (!($time > $time1330 && $time < $time24)) {
                return $this->returnJson(1002, '还没到开始时间');
            } else {
                $cacheOrder = Cache::get('create_user_order_info' . $cat_id);
                if ($cacheOrder * $sellGoodsNum >= $shopSellNum[4]) {
                    return $this->returnJson(1002, '已经被抢购完毕！');
                } else {
                    Cache::inc('create_user_order_info' . $cat_id);
                }
            }
        }
        if ($cat_id == 5) {
            //城区府前街以北（不含鑫海韵通百货）
            if (!($time > $time14 && $time < $time24)) {
                return $this->returnJson(1002, '还没到开始时间');
            } else {
                $cacheOrder = Cache::get('create_user_order_info' . $cat_id);
                if ($cacheOrder * $sellGoodsNum >= $shopSellNum[5]) {
                    return $this->returnJson(1002, '已经被抢购完毕！');
                } else {
                    Cache::inc('create_user_order_info' . $cat_id);
                }
            }
        }


        $param = $request::only(['shopName', 'shopId', 'type', 'idcard', 'mobile', 'name']);
        $userInfo = Session('userInfo');
        if (empty($userInfo)) {
            Cache::dec('create_user_order_info' . $cat_id);
            return $this->returnJson(9001, '请登录');
        }
        $this->validate($param, 'user.kouzhao');


        //----下订单逻辑了
        $data['order_no'] = 'KZ' . time() . rand(11111, 99999);
        $data['shop_id'] = $param['shopId'];
        $data['name'] = $param['name'];
        $data['shop_name'] = $param['shopName'];
        $data['mobile'] = $param['mobile'];
        $data['people_openid'] = $userInfo['openid'];
        $data['people_name'] = $userInfo['nickname'];
        $data['headimgurl'] = $userInfo['headimgurl'];
        $data['people_cardno'] = $param['idcard'];
        $data['people_card_type'] = $param['type'];
        $data['order_time'] = toDate(time(), 'Y-m-d');
        $data['suoyin1'] = $userInfo['openid'] . $data['order_time'];
        $data['suoyin2'] = $param['idcard'] . $data['order_time'];
        $data['create_time'] = toDate(time());
        $data['update_time'] = toDate(time());

        $back = [1001, '成功'];


        Db::startTrans();
        try {

            $info = Db::name('user_order')->where('people_openid', '=', $userInfo['openid'])->whereIn('order_time', [toDate(strtotime($data['order_time']) - 86400, 'Y-m-d'), $data['order_time']])->value('order_no');

            if (!empty($info)) {
                $back = [1002, '两天内您已经下过订单！'];
            } else {

                $ret = Db::name('shop_info')->where('id', '=', $data['shop_id'])
                    ->dec('num', $sellGoodsNum)
                    ->update();
                if (!$ret) {
                    Db::rollback();
                    $back = [1002, '下单失败，请重新尝试'];
                } else {

                    $num = Db::name('shop_info')->where('id', '=', $data['shop_id'])->value('num');
                    if ($num < 0) {
                        Db::rollback();
                        $back = [1002, '当前店铺口罩已经被抢光'];
                    } else {
                        Db::name('user_order')->save($data);
                        $back = [1001, '您已经成功下单'];
                        Db::commit();
                    }
                }
            }

            if ($back[0] != 1001) {
                Cache::dec('create_user_order_info' . $cat_id);
            }

        } catch (\Exception $e) {
            $back = [1002, '每个微信号码和身份证等证件号码，每天只能预约一次！'];
            Db::rollback();
            Cache::dec('create_user_order_info' . $cat_id);
        }

        return $this->returnJson($back[0], $back[1]);
    }

    public function getUserInfo()
    {
        $userInfo = Session('userInfo');
        if (empty($userInfo)) {
            return $this->returnJson(9001, '请登录');
        } else {
            return $this->returnJson(1001, '已经登录', $userInfo);
        }
    }

    public function auth(Request $request)
    {
        $url = $this->authBase();
        return redirect($url);
    }

    public function authBase()
    {
        $all = $this->request->get();
        $regist = TRUE;
        $rurl = '';
        foreach ($all as $key => $value) {
            if ($key == 'rurl') {
                $regist = TRUE;
                $rurl = $value;
            } else {
                if (strstr($rurl, '?')) {
                    $rurl = $rurl . '&' . $key . '=' . $value;
                } else {
                    $rurl = $rurl . '?' . $key . '=' . $value;
                }
            }
        }
        if ($regist == FALSE) {
            $this->errorDisplay('页面调用错误', '请传递授权页面');
        }
        $ts = time() . rand(1000, 9999);
        \mikkle\tp_master\Cache::set($ts, array('rurl' => $rurl), 20);

        $myurl = (string)url('/wl/auth2')->domain(self::$url);
        $myurl = str_replace(':80', '', $myurl);
        $myurl = str_replace(':443', '', $myurl);

        if (strpos($myurl, 'sst.trip') !== false) {
            if (!strpos($myurl, 'https')) {
                $myurl = str_replace('http', 'https', $myurl);
            }
        }

        $res = $this->getcodeUrl($ts, $myurl, 1);
        return $res;
    }

    public function getcodeUrl($rurl, $myurl, $wxid)
    {
        if (empty($myurl)) {
            $myurl = urlencode('http://sylyx.cn/index.php/Wx/getInfoAouth');//只要是授权域名之下的地址就可以
        } else {
            $myurl = urlencode($myurl);
        }
        $option = $this->getOption();
        $url = "https://open.weixin.qq.com/connect/oauth2/authorize?appid=" . $option['appid'] . "&redirect_uri=" . $myurl . "&response_type=code&scope=snsapi_userinfo&state=" . $rurl . "#wechat_redirect";
        return $url;
    }

    public function auth2(Request $request)
    {
        $code = $request::get('code');
        $state = $request::get('state');
        $resurl = '';
        $userInfo = $this->getWyInfo($code, 1);
        Session('userInfo', $userInfo);
        $url = \mikkle\tp_master\Cache::get($state);
        $url['rurl'] = str_replace("$", "#", $url['rurl']);
        return redirect($url['rurl']);
    }


    public function getWyInfo($code, $id)
    {
        $accid = $this->getTokenANDopenid($code, $id);
        if (empty($accid['access_token'])) {
            throw new \think\Exception('获取access_token失败', 10006);
        }
        $url = 'https://api.weixin.qq.com/sns/userinfo?access_token=' . $accid['access_token'] . '&openid=' . $accid['openid'] . '&lang=zh_CN';
        $res = json_decode(httpGet($url), TRUE);
        $this->setE('getWyInfo', ReturnWxError($res));
        return $res;

    }

    public function getTokenANDopenid($code, $id)
    {
        if (empty($code) && empty($id)) {
            $res = FALSE;
        } else {
            $res = $this->getWyAccessToken($id, $code);
        }
        $this->setE('getTokenANDopenid', ReturnWxError($res));
        return $res;
    }

    protected function getWyAccessToken($id, $code)
    {
        try {

            $option = $this->getOption();
            $appId = $option['appid'];
            $appSecret = $option['secret'];
            $url = "https://api.weixin.qq.com/sns/oauth2/access_token?appid=$appId&secret=$appSecret&code=$code&grant_type=authorization_code";
            $access_token = json_decode(httpGet($url), TRUE);
            return $access_token;
        } catch (Exception $e) {
            Log::error($e->getMessage());
        }
    }

    public function setE($funs, $errcode)
    {
        if ($errcode) {
            if ($errcode != 'ok') {
                Log::record('函数[' . $funs . ']' . '错误代码【' . $errcode . '】', 'setE.log');
            }
        }
    }

    public function getJsAll(Request $request)
    {
        $option = $this->getOption();
        $appid = $option['appid'];
        $url = $request::post('signurl');
        $rest = $this->getSignPackage($url, $appid);
        $list = array_slice($rest, 0, 5);
        return $this->returnJson(1001, '成功', $list);
    }

    public function getSignPackage($url, $appid)
    {
        $jsapiTicket = $this->getJsApiTicket(1);
        $timestamp = time();
        $nonceStr = createNonceStr();

        // 这里参数的顺序要按照 key 值 ASCII 码升序排序
        $string = "jsapi_ticket=$jsapiTicket&noncestr=$nonceStr&timestamp=$timestamp&url=$url";

        $signature = sha1($string);

        $signPackage = array(
            "appId" => $appid,
            "nonceStr" => $nonceStr,
            "timestamp" => $timestamp,
            "url" => $url,
            "signature" => $signature,
            "rawString" => $string
        );
        return $signPackage;
    }

    public function getJsApiTicket($wxid, $type = 'jsapi')
    {

        $wxchat_info = Cache::get('wx_chat_jsapi_ticket');

        $ticket = false;
        if ($wxchat_info != FALSE) {
            $expire = $wxchat_info['datetime'] + 7000;
            $ticket = $wxchat_info['ticket'];
            if ($expire < time()) {//过期了

                $accessToken = $this->getAccessToken();
                $url = "https://api.weixin.qq.com/cgi-bin/ticket/getticket?type=$type&access_token=$accessToken";
                $res = json_decode(httpGet($url), TRUE);
                $errmsg = $res['errmsg'];
                if ($errmsg == 'ok') {
                    $data = array('datetime' => time(), 'ticket' => $res['ticket']);
                    Cache::set('wx_chat_jsapi_ticket', $data);
                    $ticket = $res['ticket'];
                }
            }
        } else {
            $accessToken = $this->getAccessToken();
            $url = "https://api.weixin.qq.com/cgi-bin/ticket/getticket?type=$type&access_token=$accessToken";
            $res = json_decode(httpGet($url), TRUE);
            $errmsg = $res['errmsg'];
            if ($errmsg == 'ok') {
                $data = array('datetime' => time(), 'ticket' => $res['ticket']);
                Cache::set('wx_chat_jsapi_ticket', $data);
                $ticket = $res['ticket'];
            }
        }

        return $ticket;
    }

    public function getAccessToken()
    {


        $wxchat_info = Cache::get('wx_chat_access_token_');

        $option = $this->getOption();
        if ($wxchat_info != FALSE) {
            $expire = $wxchat_info['datetime'] + 7000;
            $token = $wxchat_info['token'];

            if ($expire < time()) {//过期了

                $appId = $option['appid'];
                $appSecret = $option['secret'];
                $url = "https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid=$appId&secret=$appSecret";
                $res = json_decode(httpGet($url), TRUE);
                if (!empty($res['access_token'])) {
                    $access_token = $res['access_token'];
                } else {
                    $access_token = $token = false;
                }
                if ($access_token) {
                    $data = array('datetime' => time(), 'token' => $access_token);
                    Cache::set('wx_chat_access_token_', $data);
                    $token = $access_token;
                }

            }
        } else {
            $appId = $option['appid'];
            $appSecret = $option['secret'];
            $url = "https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid=$appId&secret=$appSecret";
            $res = json_decode(httpGet($url), TRUE);
            if (!empty($res['access_token'])) {
                $access_token = $res['access_token'];
            } else {
                $access_token = $token = false;
            }
            if ($access_token) {
                $data = array('datetime' => time(), 'token' => $access_token);
                Cache::set('wx_chat_access_token_', $data);
                $token = $access_token;
            }

        }

        return $token;
    }

    /**
     * 自己的订单列表
     * @return \think\Response
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\DbException
     * @throws \think\db\exception\ModelNotFoundException
     */
    public function orderList()
    {
        $userInfo = Session('userInfo');
        if (empty($userInfo)) {
            return $this->returnJson(9001, '请登录');
        }
        //        $userInfo['openid'] = 'otkpj1sLIyZZBenfw5-5-7jOYLd8';
        $list = Db::name('user_order')->alias('a')->where('a.people_openid', '=', $userInfo['openid'])->leftJoin('shop_info b', 'a.shop_id=b.id')->field('a.*,b.address,b.shop_open_time')->order('a.state')->select();
        return $this->returnJson(1001, 'ok', $list);
    }

    /**
     * 查询自己消票的列表
     * @return \think\Response
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\DbException
     * @throws \think\db\exception\ModelNotFoundException
     */
    public function checkOrderList()
    {
        $userInfo = Session('userInfo');
        if (empty($userInfo)) {
            return $this->returnJson(9001, '请登录');
        }
        //        $list = Db::name('user_order')->where('check_user', '=', $userInfo['openid'])->select();
        $list = Db::name('user_order')->alias('a')->leftJoin('shop_info b', 'a.shop_id=b.id')->where('a.check_user', '=', $userInfo['openid'])->field('a.*,b.address')->order('a.state')->select();
        return $this->returnJson(1001, 'ok', $list);
    }

    /**
     * 根据时间查询所有的消票订单
     * @return \think\Response
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\DbException
     * @throws \think\db\exception\ModelNotFoundException
     */
    public function checkOrderTimeList(Request $request)
    {
        $beginTime = $request::get('beginTime');
        $endTime = $request::get('endTime');
        $userInfo = Session('userInfo');
        //        $userInfo['openid'] = 'otkpj1gHKLqTev3_4nxu4FJ7BSDQ';
        if (empty($userInfo)) {
            return $this->returnJson(9001, '请登录');
        }

        $shopUser = Db::name('shop_user')->
        where('openid', '=', $userInfo['openid'])->value('shop_id');
        if (empty($shopUser)) {
            return $this->returnJson(1002, '您不是核验人员');
        }

        //        $list = Db::name('user_order')->where('check_user', '=', $userInfo['openid'])->select();
        $list = Db::name('user_order')->alias('a')->
        leftJoin('shop_info b', 'a.shop_id=b.id')->
        where('a.shop_id', '=', $shopUser)->
        whereTime('a.create_time', 'between', [$beginTime, $endTime])->
        field('a.headimgurl,a.order_no,a.state,a.shop_name,b.shop_open_time,a.create_time,b.address')->order('a.state')->select();
        return $this->returnJson(1001, 'ok', $list);
    }

    /**
     * 管理员订单列表
     * @return \think\Response
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\DbException
     * @throws \think\db\exception\ModelNotFoundException
     */
    public function managerOrderList()
    {
        $userInfo = Session('userInfo');
        if (empty($userInfo)) {
            return $this->returnJson(9001, '请登录');
        }
        if (in_array($userInfo['openid'], ['otkpj1oDiFIUMGJvx5BqSvO-qGHw', 'otkpj1oDrmUVx8OH7o01di76MGQM'])) {
            $list = Db::name('user_order')->alias('a')->leftJoin('shop_info b', 'a.shop_id=b.id')->field('a.*,b.address')->order('a.state')->select();
            return $this->returnJson(1001, 'ok', $list);
        } else {
            return $this->returnJson(1002, '没有权限');
        }

    }

    public function delOrder(Request $request)
    {
        $id = $request::get('id');
        $userInfo = Session('userInfo');
        if (empty($userInfo)) {
            return $this->returnJson(9001, '请登录');
        }
        if (in_array($userInfo['openid'], ['otkpj1oDiFIUMGJvx5BqSvO-qGHw', 'otkpj1oDrmUVx8OH7o01di76MGQM'])) {
            $list = Db::name('user_order')->where('id', '=', $id)->delete();
            return $this->returnJson(1001, '删除成功');
        } else {
            return $this->returnJson(1002, '没有权限');
        }
    }

    /**
     * 消码
     */
    public function checkOrder(Request $request)
    {
        $code = $request::get('code');
        $idCard = $request::get('idcard');
        if (!empty($idCard)) {
            $where['people_cardno'] = $idCard;
            $where['state'] = 1;
        } else {
            $where['order_no'] = $code;
        }

        $userInfo = Session('userInfo');
        if (empty($userInfo)) {
            return $this->returnJson(9001, '请登录');
        }

        //        $userInfo['openid'] = 'otkpj1oDrmUVx8OH7o01di76MGQM';

        $shopUser = Db::name('shop_user')->where('openid', '=', $userInfo['openid'])->value('shop_id');
        if (empty($shopUser)) {
            return $this->returnJson(1002, '您不是核验人员');
        }

        $ret = Db::name('user_order')->where($where)->find();

        if ($ret) {
            $date = toDate(time() - 86400, 'Y-m-d');
            $begin = strtotime($date . '00:00:00');
            $end = strtotime($date . '23:59:59');

            if (!(strtotime($ret['create_time']) > $begin && strtotime($ret['create_time']) < $end)) {
                return $this->returnJson(1002, '明天才能核验！');
            }

            if ($ret['state'] == 2) {
                return $this->returnJson(1002, '此订单已经验证过');
            }
            if ($ret['shop_id'] != $shopUser) {
                return $this->returnJson(1002, '这个不是您网点的订单');
            }
            $result = Db::name('user_order')->where($where)->update(['state' => 2, 'check_user' => $userInfo['openid']]);
            if ($result) {
                return $this->returnJson(1001, '核验成功');
            } else {
                return $this->returnJson(1002, '核验失败，请重试');

            }
        } else {
            return $this->returnJson(1002, '订单号不正确');
        }

    }

    public function getOrderInfo(Request $request)
    {
        $code = $request::get('code');
        $ret = Db::name('user_order')->where('order_no', '=', $code)->find();
        if ($ret) {

            return $this->returnJson(1001, '获取数据', $ret);
        } else {
            return $this->returnJson(1002, '失败');
        }
    }

    /**
     * 是否是消票人员
     * @return \think\Response
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\DbException
     * @throws \think\db\exception\ModelNotFoundException
     */
    public function isBindShopUser()
    {
        $userInfo = Session('userInfo');
        if (empty($userInfo)) {
            return $this->returnJson(9001, '请登录');
        }
        $shopUser = Db::name('shop_user')->alias('a')->leftJoin('shop_info b', 'a.shop_id=b.id')->where('a.openid', '=', $userInfo['openid'])->field('a.*,b.shop_name')->find();
        if (empty($shopUser)) {
            return $this->returnJson(1002, '请绑定核验人员');
        } else {
            $total = Db::name('user_order')->where('shop_id', '=', $shopUser['shop_id'])->field('state,count(*) as total')->group('state')->select()->toArray();
            $all = 0;
            $used = 0;
            $over = 0;
            foreach ($total as $value) {

                if ($value['state'] == 2) {
                    $used = $value['total'];
                }
                if ($value['state'] == 3) {
                    $over = $value['total'];
                }
                $all += $value['total'];
            }
            return $this->returnJson(1001, '正确', ['user' => $shopUser, 'used' => $used, 'over' => $over, 'all' => $all]);
        }
    }

    /**
     * 绑定店铺用户
     */
    public function bindShopUser(Request $request)
    {
        $param = $request::only(['name', 'mobile', 'account', 'pwd']);
        $userInfo = Session('userInfo');
        if (empty($userInfo)) {
            return $this->returnJson(9001, '请登录');
        }
        $this->validate($param, 'user.bangding');
        $find = Db::name('shop_info')->where(['account' => $param['account'], 'pwd' => $param['pwd']])->find();
        if (empty($find)) {
            return $this->returnJson(1002, '账号密码错误');
        } else {
            $data['openid'] = $userInfo['openid'];
            $data['shop_id'] = $find['id'];
            $data['nickname'] = $userInfo['nickname'];
            $data['headimgurl'] = $userInfo['headimgurl'];
            $data['name'] = $param['name'];
            $data['mobile'] = $param['mobile'];
            $ret = Db::name('shop_user')->save($data);
            if ($ret) {
                return $this->returnJson(1001, '绑定成功可以验票了');
            } else {
                return $this->returnJson(1002, '您已经绑定过了');
            }
        }
    }

    public function createShopPwd()
    {
        $list = Db::name('shop_info')->select();
        foreach ($list as $key => $value) {
            $data['account'] = 'yd00' . $key;
            $data['pwd'] = 'yd' . rand(1111, 9999);
            Db::name('shop_info')->where('id', '=', $value['id'])->update($data);
        }
    }

    /*
     * 判断用户是否关注公众号
     */
    public function isSubscribe()
    {
        $userInfo = Session('userInfo');
        if (empty($userInfo)) {
            return $this->returnJson(9001, '请登录');
        }
        $info = $this->getWxUserInfo($userInfo['openid']);
        if ($info['subscribe'] == 1) {
            return $this->returnJson(1001, '已经关注');
        } else {
            return $this->returnJson(1002, '没有关注');
        }
    }

    /**
     * 函数说明：根据openid获取用户的详细信息
     *
     * @param string $code
     *
     * @return object
     * @author mike<stardandan@126.com>
     *
     * @deprecated 创建时间：2017-2-21
     * @deprecated 备注：
     */
    public function getWxUserInfo($openid)
    {
        $accessToken = $this->getAccessToken();
        $url = "https://api.weixin.qq.com/cgi-bin/user/info?access_token=$accessToken&openid=$openid&lang=zh_CN";
        $res = json_decode(httpGet($url), TRUE);
        $this->setE('getWxUserInfo', ReturnWxError($res));
        return $res;

    }

    protected function getOption()
    {
        return Config::get('wechat.' . Config::get('wechat.default_options_name'));
    }

    public function updateDateOrder()
    {
        $date = toDate(time() - 86400 * 2, 'Y-m-d') . ' 23:59:59';
        $ret = Db::name('user_order')->whereTime('create_time', '<', $date)->where('state', '=', '1')->update(['state' => 3]);
        //        Db::listen(function($sql, $runtime, $master) {
        //
        //        });
    }

    public function lunXun()
    {
        $date = toDate(time() - 86400, 'Y-m-d');
        //        $ret = Db::name('shop_info')->where('num', '<=', 800)->update(['num' => 800]);
        $list = Db::name('shop_info')->where('is_open', '=', 1)->field('category,sum(num) as total')->group('category')->select();

        $shopNum = [];
        foreach ($list as $key => $value) {
            $shopNum[$value['category']] = $value['total'];
        }
        Cache::set('shopSellTotalNum', $shopNum);

        Cache::set('create_user_order_info1', 0);
        Cache::set('create_user_order_info2', 0);
        Cache::set('create_user_order_info3', 0);
        Cache::set('create_user_order_info4', 0);
        Cache::set('create_user_order_info5', 0);
    }

    public function showConfig()
    {
        $num = Cache::get('shopSellTotalNum');

        $num[1] = empty($num[1]) ? 0 : $num[1];
        $num[2] = empty($num[2]) ? 0 : $num[2];
        $num[3] = empty($num[3]) ? 0 : $num[3];
        $num[4] = empty($num[4]) ? 0 : $num[4];
        $num[5] = empty($num[5]) ? 0 : $num[5];

        $sellNum1 = Cache::get('create_user_order_info1');
        $sellNum2 = Cache::get('create_user_order_info2');
        $sellNum3 = Cache::get('create_user_order_info3');
        $sellNum4 = Cache::get('create_user_order_info4');
        $sellNum5 = Cache::get('create_user_order_info5');

        $list = Db::name('user_order')->alias('a')->where('a.order_time', '=', toDate(time(), 'Y-m-d'))
            ->leftJoin('shop_info b', 'a.shop_id=b.id')
            ->field('count(a.id) as total,b.category')->group('b.category')->select();

        $nowOrderNum[1] = 0;
        $nowOrderNum[2] = 0;
        $nowOrderNum[3] = 0;
        $nowOrderNum[4] = 0;
        $nowOrderNum[5] = 0;
        foreach ($list as $value) {
            if ($value['category'] == 1) {
                $nowOrderNum[1] = $value['total'];
            }
            if ($value['category'] == 2) {
                $nowOrderNum[2] = $value['total'];
            }
            if ($value['category'] == 3) {
                $nowOrderNum[3] = $value['total'];
            }
            if ($value['category'] == 4) {
                $nowOrderNum[4] = $value['total'];
            }
            if ($value['category'] == 5) {
                $nowOrderNum[5] = $value['total'];
            }
        }

        $selfnum = self::$sellNum;

        $sellToNum1 = $sellNum1 * $selfnum;
        $sellToNum2 = $sellNum2 * $selfnum;
        $sellToNum3 = $sellNum3 * $selfnum;
        $sellToNum4 = $sellNum4 * $selfnum;
        $sellToNum5 = $sellNum5 * $selfnum;

        return "<h1>马坡-牛山：已经购买订单$sellNum1 * $selfnum=$sellToNum1</h1>【总数：$num[1]】----当前订单总数【$nowOrderNum[1]】</br>
                <h1>河东镇:已经购买订单$sellNum2* $selfnum=$sellToNum2</h1>【总数：$num[2]】----当前订单总数【$nowOrderNum[2]】</br>
                <h1>城区府前街以南（含鑫海韵通百货）:已经购买订单$sellNum3* $selfnum=$sellToNum3</h1>【总数：$num[3]】----当前订单总数【$nowOrderNum[3]】</br>
                <h1>河西镇街（除以上地区）:已经购买订单$sellNum4* $selfnum=$sellToNum4</h1>【总数：$num[4]】----当前订单总数【$nowOrderNum[4]】</br>
                <h1>城区府前街以北（不含鑫海韵通百货）:已经购买订单$sellNum5* $selfnum=$sellToNum5</h1>【总数：$num[5]】----当前订单总数【$nowOrderNum[5]】</br>
                </br>
                </br>
                </br>
                </br>
                </br>
                </br>
                <a href='http://kouzhao.wanglanglang.com/wl/updateDuiLie' >点击更新可卖数据</a>
                ";
    }

    /**
     * 更新订单数和redis里面的数量不一致问题
     */
    public function updateDuiLie()
    {
        $num = Cache::get('shopSellTotalNum');

        //---总数量
        $num[1] = empty($num[1]) ? 0 : $num[1];
        $num[2] = empty($num[2]) ? 0 : $num[2];
        $num[3] = empty($num[3]) ? 0 : $num[3];
        $num[4] = empty($num[4]) ? 0 : $num[4];
        $num[5] = empty($num[5]) ? 0 : $num[5];

        $list = Db::name('user_order')->alias('a')->where('a.order_time', '=', toDate(time(), 'Y-m-d'))
            ->leftJoin('shop_info b', 'a.shop_id=b.id')
            ->field('count(a.id) as total,b.category')->group('b.category')->select();

        $sellNum1 = Cache::get('create_user_order_info1');
        $sellNum2 = Cache::get('create_user_order_info2');
        $sellNum3 = Cache::get('create_user_order_info3');
        $sellNum4 = Cache::get('create_user_order_info4');
        $sellNum5 = Cache::get('create_user_order_info5');

        $sellNum = self::$sellNum;

        foreach ($list as $value) {
            if ($value['category'] == 1) {
                $nowOrderNum[1] = $value['total'];
                if ($sellNum1 * $sellNum == $num[1]) {
                    if($nowOrderNum[1]< $sellNum1){
                        Cache::set('create_user_order_info1',$sellNum1-($sellNum1-$nowOrderNum[1]));
                        echo '马坡-牛山【订单数量和最大限制数相差'.($sellNum1-$nowOrderNum[1]).'】个===已经更新</br>';
                    }
                }
            }
            if ($value['category'] == 2) {
                $nowOrderNum[2] = $value['total'];
                if ($sellNum2 * $sellNum == $num[2]) {
                    if($nowOrderNum[2]< $sellNum2){
                        Cache::set('create_user_order_info2',$sellNum2-($sellNum2-$nowOrderNum[2]));
                        echo '河东镇【订单数量和最大限制数相差'.($sellNum2-$nowOrderNum[2]).'】个===已经更新</br>';
                    }
                }
            }
            if ($value['category'] == 3) {
                $nowOrderNum[3] = $value['total'];
                if ($sellNum3 * $sellNum == $num[3]) {
                    if($nowOrderNum[3]< $sellNum3){
                        Cache::set('create_user_order_info3',$sellNum3-($sellNum3-$nowOrderNum[3]));
                        echo '城区府前街以南（含鑫海韵通百货）【订单数量和最大限制数相差'.($sellNum3-$nowOrderNum[3]).'】个===已经更新</br>';
                    }
                }
            }
            if ($value['category'] == 4) {
                $nowOrderNum[4] = $value['total'];
                if ($sellNum4 * $sellNum == $num[4]) {
                    if($nowOrderNum[4]< $sellNum4){
                        Cache::set('create_user_order_info4',$sellNum4-($sellNum4-$nowOrderNum[4]));
                        echo '河西镇街（除以上地区）【订单数量和最大限制数相差'.($sellNum4-$nowOrderNum[4]).'】个===已经更新</br>';
                    }
                }
            }
            if ($value['category'] == 5) {
                $nowOrderNum[5] = $value['total'];
                if ($sellNum5 * $sellNum == $num[5]) {
                    if($nowOrderNum[5]< $sellNum5){
                        Cache::set('create_user_order_info5',$sellNum5-($sellNum5-$nowOrderNum[5]));
                        echo '城区府前街以北（不含鑫海韵通百货）【订单数量和最大限制数相差'.($sellNum5-$nowOrderNum[5]).'】个===已经更新</br>';
                    }
                }
            }
        }
    }

    public function tt()
    {
        $list = $this->getOption();
        dump($list);
    }

    public function tt2(Request $request)
    {
        $cat_id = 1;

        $time = time();
        $date = toDate($time, 'Y-m-d');
        $time12 = strtotime($date . ' 12:00:00');
        $time1230 = strtotime($date . ' 12:30:00');
        $time13 = strtotime($date . ' 13:00:00');
        $time1330 = strtotime($date . ' 13:30:00');
        $time14 = strtotime($date . ' 14:00:00');

        $time24 = strtotime($date . ' 23:59:00');


        $shopSellNum[1] = 1000;

        $sellGoodsNum = 5;

        //马坡-牛山
        if ($cat_id == 1) {
            if (!($time > $time12 && $time < $time24)) {
                return $this->returnJson(1002, '还没到开始时间');
            } else {
                $cacheOrder = Cache::get('create_user_order_info100' . $cat_id);
                if ($cacheOrder * $sellGoodsNum >= $shopSellNum[1]) {
                    return $this->returnJson(1002, '已经被抢购完毕！');
                } else {
                    Cache::inc('create_user_order_info100' . $cat_id);
                }
            }
        }


        $param = $request::only(['shopName', 'shopId', 'type', 'idcard', 'mobile', 'name']);


        $str = createNonceStr(32);


        //----下订单逻辑了
        $data['order_no'] = 'KZ' . time() . rand(11111, 99999);
        $data['shop_id'] = 141;
        $data['name'] = time();
        $data['shop_name'] = '2';
        $data['mobile'] = '2';
        $data['people_openid'] = $str;
        $data['people_name'] = $str;
        $data['headimgurl'] = '';
        $data['people_cardno'] = $str;
        $data['people_card_type'] = 1;
        $data['order_time'] = toDate(time(), 'Y-m-d');
        $data['suoyin1'] = $str . $data['order_time'];
        $data['suoyin2'] = $str . $data['order_time'];
        $data['create_time'] = toDate(time());
        $data['update_time'] = toDate(time());

        $back = [1001, '成功'];


        Db::startTrans();
        try {

            $info = false;

            if (!empty($info)) {
                $back = [1002, '两天内您已经下过订单！'];
            } else {

                $ret = Db::name('shop_info_copy1')->where('id', '=', $data['shop_id'])
                    ->dec('num', 5)
                    ->update();
                echo '减少5个库存</br>';
                if (!$ret) {
                    Db::rollback();
                    $back = [1002, '下单失败，请重新尝试'];
                } else {

                    $num = Db::name('shop_info_copy1')->where('id', '=', $data['shop_id'])->value('num');
                    echo "查询库存数量$num</br>";
                    if ($num < 0) {
                        Db::rollback();
                        $back = [1002, '当前店铺口罩已经被抢光'];
                    } else {
                        Db::name('user_order_copy1')->save($data);
                        $back = [1001, '您已经成功下单'];
                        Db::commit();
                    }
                }
            }

            if ($back[0] != 1001) {
                Cache::dec('create_user_order_info100' . $cat_id);
            }

        } catch (\Exception $e) {
            $back = [1002, '每个微信号码和身份证等证件号码，每天只能预约一次！'];
            Db::rollback();
            Cache::dec('create_user_order_info100' . $cat_id);
        }

        return $this->returnJson($back[0], $back[1]);
    }

    /**
     * 在info_base表里面取num更新到shaop_info里面
     */
    public function updateBaseInfoToInfo(){
        $list = Db::name('shop_info_base')->field('id,num')->select()->toArray();
        foreach ($list as $value){
            Db::name('shop_info')->where('id','=',$value['id'])->update(['num'=>$value['num']]);
        }
    }

}
